package cn.com.do1.component.merchant.merchant.ui;

import cn.com.do1.common.dac.Pager;
import cn.com.do1.common.annotation.struts.*;
import cn.com.do1.common.framebase.struts.BaseAction;
import cn.com.do1.component.merchant.merchant.model.*;
import cn.com.do1.component.merchant.merchant.service.IMerchantService;
import cn.com.do1.component.merchant.merchant.vo.TbCzMerchantListVO;
import cn.com.do1.component.merchant.merchant.vo.TbCzMerchantVO;
import cn.com.do1.component.systemmgr.person.model.PersonVO;
import cn.com.do1.component.systemmgr.person.service.IPersonService;
import cn.com.do1.component.systemmgr.user.model.BaseUserVO;
import cn.com.do1.component.systemmgr.user.model.User;
import cn.com.do1.component.systemmgr.user.model.UserVO;
import cn.com.do1.component.systemmgr.user.service.IUserService;
import cn.com.do1.component.util.ExcelUtil;

import org.apache.struts2.ServletActionContext;

import cn.com.do1.common.exception.BaseException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.text.DecimalFormat;

import cn.com.do1.common.util.AssertUtil;
import cn.com.do1.common.util.DateUtil;
import cn.com.do1.common.util.reflation.BeanHelper;
import cn.com.do1.common.util.security.SecurityUtil;
import cn.com.do1.dqdp.core.ConfigMgr;
import cn.com.do1.dqdp.core.DqdpAppContext;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Copyright &copy; 2010 广州市道一信息技术有限公司 All rights reserved. User: ${user}
 */
public class MerchantAction extends BaseAction {
    private final static transient Logger logger = LoggerFactory.getLogger(MerchantAction.class);

    private TbCzMerchantPO tbCzMerchantPO;
    private TbCzMerchantVO merchantVO;
    private String ids[];
    private String id;
    private PersonVO personVO;
    private UserVO userVO;
    private BaseUserVO baseUserVO;
    private Map myPersonMap;
    private String personId;
    private String userId;
    private String newPassword;
    private String orgId;
    private String status;

    private IMerchantService merchantService;

    private IPersonService myPersonService;

    private IUserService userService;

    @Resource
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }


    @Resource
    public void setMerchantService(IMerchantService merchantService) {
        this.merchantService = merchantService;
    }

    @Resource
    public void setMyPersonService(IPersonService myPersonService) {
        this.myPersonService = myPersonService;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getNewPassword() {
        return newPassword;
    }


    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String[] getIds() {
        return ids;
    }

    public void setIds(String[] ids) {
        this.ids = ids;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


    public PersonVO getPersonVO() {
        return personVO;
    }

    public void setPersonVO(PersonVO personVO) {
        this.personVO = personVO;
    }

    public UserVO getUserVO() {
        return userVO;
    }

    public void setUserVO(UserVO userVO) {
        this.userVO = userVO;
    }

    public BaseUserVO getBaseUserVO() {
        return baseUserVO;
    }

    public void setBaseUserVO(BaseUserVO baseUserVO) {
        this.baseUserVO = baseUserVO;
    }

    public Map getMyPersonMap() {
        return myPersonMap;
    }

    public void setMyPersonMap(Map myPersonMap) {
        this.myPersonMap = myPersonMap;
    }

    public TbCzMerchantPO getTbCzMerchantPO() {
        return tbCzMerchantPO;
    }


    public String getPersonId() {
        return personId;
    }

    public void setPersonId(String personId) {
        this.personId = personId;
    }


    public TbCzMerchantVO getMerchantVO() {
        return merchantVO;
    }

    public void setMerchantVO(TbCzMerchantVO merchantVO) {
        this.merchantVO = merchantVO;
    }


    public String getOrgId() {
        return orgId;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * 列表查询时，页面要传递的参数
     */
    @SearchValueTypes(nameFormat = "false", value = {
            @SearchValueType(name = "testDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "mobile", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "discount", type = "number"), @SearchValueType(name = "money", type = "number"),
            @SearchValueType(name = "testString", type = "string", format = "%%%s%%")})
    @JSONOut(catchException = @CatchException(errCode = "1001", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxSearch() throws Exception, BaseException {
        Pager pager = new Pager(ServletActionContext.getRequest(), getPageSize());
        pager = merchantService.searchMerchant(getSearchValue(), pager);
        addJsonPager("pageData", pager);
    }

    @JSONOut(catchException = @CatchException(errCode = "1002", successMsg = "新增成功", faileMsg = "新增失败"))
    public void ajaxAdd() throws Exception, BaseException {
        // todo:完成新增的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1003", successMsg = "更新成功", faileMsg = "更新失败"))
    public void ajaxUpdate() throws Exception, BaseException {
        // todo:完成更新的代码;
    }

    @JSONOut(catchException = @CatchException(errCode = "1004", successMsg = "删除成功", faileMsg = "删除失败"))
    public void ajaxBatchDelete() throws Exception, BaseException {
        // 完成批量更新的代码
    }

    public void setTbCzMerchantPO(TbCzMerchantPO tbCzMerchantPO) {
        this.tbCzMerchantPO = tbCzMerchantPO;
    }

    public TbCzMerchantPO setTbCzMerchantPO() {
        return this.tbCzMerchantPO;
    }

    public void addTbCzMerchantPO() {
        super.ajaxAdd(tbCzMerchantPO);
    }

    public void updateTbCzMerchantPO() {
        super.ajaxUpdate(tbCzMerchantPO);
    }

    public void deleteTbCzMerchantPO() {
        if (AssertUtil.isEmpty(id))
            id = ids[0];
        tbCzMerchantPO._setPKValue(id);
        super.ajaxDelete(tbCzMerchantPO);
    }

    public void batchDeleteTbCzMerchantPO() {
        super.ajaxBatchDelete(TbCzMerchantPO.class, ids);
    }

    @JSONOut(catchException = @CatchException(errCode = "1005", successMsg = "查询成功", faileMsg = "查询失败"))
    public void ajaxView() throws Exception, BaseException {

        TbCzMerchantPO xxPO = merchantService.searchByPk(TbCzMerchantPO.class, id);
        addJsonFormateObj("tbCzMerchantPO", xxPO);// 注意，PO才用addJsonFormateObj，如果是VO，要采用addJsonObj
    }

    @ActionRoles({"userAdd"})
    public void addPerson() {
        if (Float.parseFloat(merchantVO.getDiscount()) < ConfigMgr.getFloatCfg("systemmgr", "discount", 50)) {
            setActionResult("1913", "折扣率不能低于" + ConfigMgr.get("systemmgr", "discount", "50") + "%");
        } else {
            try {
                User user = (User) DqdpAppContext.getCurrentUser();
                merchantVO.setOper(user.getUsername());
                merchantVO.setInsertDate(DateUtil.formartCurrentDateTime());
                merchantService.addPerson(personVO, userVO, merchantVO, myPersonMap);
                setActionResult("0", "新增商户信息成功");
            } catch (SQLException e) {
                logger.error("新增商户信息记录失败", e);
                setActionResult("1913", "添加商户信息失败");
            } catch (Exception e) {
                logger.error("新增商户信息记录失败", e);
                setActionResult("1913", "添加商户信息失败");
            } catch (BaseException e) {
                logger.error("新增商户信息记录失败", e);
                setActionResult("1913", "添加商户信息失败");
            }
        }

        doJsonOut();
    }

    @ActionRoles({"userView"})
    public void viewBaseUserDetailVO() {

        if (!AssertUtil.isEmpty(this.personId)) {
            try {
                addJsonObj("baseUserVO", this.myPersonService.getBaseUserVOByPersonId(this.personId));
                addJsonObj("myPersonMap", this.myPersonService.viewMyPersonByID(this.personId));
                addJsonObj("merchantVO", this.merchantService.getMerchantDetailByPersonId(this.personId));
                setActionResult("0", "查询成功");
            } catch (BaseException e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            } catch (Exception e) {
                logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
                setActionResult("1001", "查询用户信息失败");
            }
        }
        doJsonOut();
    }

    @ActionRoles({"userView"})
    public void viewBaseUserVO() {

        try {
            addJsonObj("baseUserVO", this.myPersonService.getBaseUserVOByPersonId(this.personId));
            addJsonObj("myPersonMap", this.myPersonService.viewMyPersonByID(this.personId));
            TbCzMerchantVO merchantVO = this.merchantService.getMerchantByPersonId(this.personId);
            DecimalFormat df = new DecimalFormat("0");
            merchantVO.setDiscount(df.format(Float.parseFloat(merchantVO.getDiscount()) * 100));// 设置百分率
            addJsonObj("merchantVO", merchantVO);
            setActionResult("0", "查询成功");
        } catch (BaseException e) {
            logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
            setActionResult("1001", "查询用户信息失败");
        } catch (Exception e) {
            logger.error("查找人员关联的用户信息时发生异常,personId:" + this.personId, e);
            setActionResult("1001", "查询用户信息失败");
        }
        doJsonOut();
    }

    @ActionRoles({"userDel"})
    public void delPerson() {
        try {
            this.merchantService.delPerson(this.ids);
            setActionResult("0", "删除人员信息成功");
        } catch (Exception e) {
            logger.error("删除人员记录时发生异常", e);
            setActionResult("1914", "删除人员信息失败");
        } catch (BaseException e) {
            logger.error("删除人员记录时发生异常", e);
            setActionResult("1914", "删除人员信息失败");
        }
        doJsonOut();
    }

    @ActionRoles({"userDel"})
    public void delBaseUser() {
        try {
            this.merchantService.delBaseUserByPersonId(this.ids);
            setActionResult("0", "删除用户成功");
        } catch (Exception e) {
            logger.error("删除用户异常", e);
            setActionResult("1001", "删除失败");
        } catch (BaseException e) {
            logger.error("删除用户异常", e);
            setActionResult("1001", "删除失败");
        }
        doJsonOut();
    }

    @ActionRoles({"userEdit"})
    public void updateAdminBaseUser() {
        try {
            User user = (User) DqdpAppContext.getCurrentUser();
            merchantVO.setOper(user.getUsername());
            merchantVO.setUpdateDate(DateUtil.formartCurrentDateTime());
            this.merchantService.updateAdminBaseUser(this.baseUserVO, this.merchantVO, this.myPersonMap);
            setActionResult("0", "修改商户信息成功");
        } catch (BaseException e) {
            logger.error("修改商户信息异常", e);
            setActionResult("1001", "修改商户信息失败");
        } catch (Exception e) {
            logger.error("修改商户信息异常", e);
            setActionResult("1001", "修改商户信息失败");
        }
        doJsonOut();
    }

    @ActionRoles({"userEdit"})
    public void updateBaseUser() {
        if (AssertUtil.isEmpty(newPassword)) {
            setActionResult("1001", "支付密码不能为空");
        }
        if (Float.parseFloat(merchantVO.getDiscount()) < ConfigMgr.getFloatCfg("systemmgr", "discount", 50)) {
            setActionResult("1913", "折扣率不能低于" + ConfigMgr.get("systemmgr", "discount", "50") + "%");
        } else {
            try {

                User user = (User) DqdpAppContext.getCurrentUser();
                TbCzMerchantVO vo = this.merchantService.getMerchantByPersonId(user.getPersonId());
                if (SecurityUtil.getMd5Code(newPassword).equals(vo.getPayPassword())) {
                    merchantVO.setOper(user.getUsername());
                    merchantVO.setUpdateDate(DateUtil.formartCurrentDateTime());
                    this.merchantService.updateBaseUser(this.baseUserVO, this.merchantVO, this.myPersonMap);
                    setActionResult("0", "修改商户信息成功");
                } else {
                    setActionResult("1001", "支付密码不正确，无法修改商户信息");
                }

            } catch (BaseException e) {
                logger.error("修改商户信息异常", e);
                setActionResult("1001", "修改商户信息失败");
            } catch (Exception e) {
                logger.error("修改商户信息异常", e);
                setActionResult("1001", "修改商户信息失败");
            }
        }

        doJsonOut();
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "支付密码修改失败", successMsg = "支付密码修改成功"))
    @ActionRoles("userPayPassword")
    public void changePayPassword() throws Exception, BaseException {
        this.merchantService.changePayPassword(this.userId, this.newPassword);
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "操作失败", successMsg = "操作成功"))
    @ActionRoles("userEdit")
    public void changeClient() throws Exception, BaseException {
        this.merchantService.changePayClient(this.userId, this.status);
    }

    @ActionRoles({"userList"})
    @SearchValueTypes({@SearchValueType(name = "startDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "endDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "mobile", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "discount", type = "number"),
            @SearchValueType(name = "userName", type = "String", format = "%%%s%%"),
            @SearchValueType(name = "personName", type = "String", format = "%%%s%%")})
    public void listPersonByOrgId() {
        Pager pager = new Pager(ServletActionContext.getRequest(), BaseAction.getPageSize());
        try {
            System.out.println("bbbbbbbbbbbbbbbbbbbb");
            pager = this.merchantService.listPersonByOrg(this.orgId, pager, getSearchValue());
            addJsonPager("userPager", pager);
            setActionResult("0", "查询成功");
        } catch (BaseException e) {
            logger.error("根据机构id获取用户列表异常", e);
            setActionResult("1001", "查询异常");
        } catch (Exception e) {
            logger.error("根据机构id获取用户列表异常", e);
            setActionResult("1001", "查询异常");
        }
        doJsonOut();
    }

    @JSONOut(catchException = @CatchException(errCode = "1001", faileMsg = "注册失败", successMsg = "注册成功"))
    public void addMerchant() throws BaseException {

        HttpServletRequest httpservletrequest = ServletActionContext.getRequest();
        String randomCode = httpservletrequest.getParameter("j_code");

        String sessionCode = (String) httpservletrequest.getSession().getAttribute("RandString");

        if (randomCode == null || !randomCode.equalsIgnoreCase(sessionCode)) {
            logger.debug("------->>验证码错误");
            setActionResult("1001", "验证码错误");
        }

        String j_username = httpservletrequest.getParameter("j_reg_username");
        ;
        String j_password = httpservletrequest.getParameter("j_reg_password");
        ;
        String j_confirmPassword = httpservletrequest.getParameter("j_reg_confirmPassword");
        ;
        String j_payPassword = httpservletrequest.getParameter("j_reg_payPassword");
        ;
        String j_confirmPayPassword = httpservletrequest.getParameter("j_reg_confirmPayPassword");
        ;
        String j_mobile = httpservletrequest.getParameter("j_reg_mobile");
        ;
        String j_qq = httpservletrequest.getParameter("j_reg_qq");
        String userIds = httpservletrequest.getParameter("userIds");
        String orgId = httpservletrequest.getParameter("orgId");
        String roleIds = httpservletrequest.getParameter("roleIds");
        String isInternal = httpservletrequest.getParameter("isInternal");

        try {
            if (this.userService.isUserAlreadyExist(j_username)) {
                logger.error(j_username + "用户已存在");
                throw new BaseException("1005", "用户已存在");
            }
        } catch (SQLException var2) {
            logger.error("查询用户是否存在时发生异常", var2);
            throw new BaseException("1005", "用户已存在");
        } catch (BaseException var3) {
            logger.error("查询用户是否存在时发生异常", var3);
            throw new BaseException("1005", "用户已存在");
        }


        this.personVO = new PersonVO();
        this.personVO.setOrgId(orgId);
        this.personVO.setPersonName(j_username);

        this.userVO = new UserVO();
        this.userVO.setUserName(j_username);
        this.userVO.setPassword(j_password);
        this.userVO.setConfirmPassword(j_confirmPassword);
        this.userVO.setIsInternal(isInternal);
        this.userVO.setRoleIds(roleIds);


        this.merchantVO = new TbCzMerchantVO();
        this.merchantVO.setPayPassword(j_payPassword);
        this.merchantVO.setMobile(j_mobile);
        this.merchantVO.setQq(j_qq);
        this.merchantVO.setOper(j_username);
        this.merchantVO.setInsertDate(DateUtil.formartCurrentDateTime());

        try {

            merchantService.addPerson(personVO, userVO, merchantVO, myPersonMap);
            setActionResult("0", "新增人员信息成功");
        } catch (SQLException e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", e.getMessage());
        } catch (Exception e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", e.getMessage());
        } catch (BaseException e) {
            logger.error("新增人员信息记录失败", e);
            setActionResult("1913", e.getMessage());
        }
    }

    @SearchValueTypes({@SearchValueType(name = "startDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "endDate", type = "date", format = "yyyy-MM-dd HH:mm:ss"),
            @SearchValueType(name = "mobile", type = "string", format = "%%%s%%"),
            @SearchValueType(name = "discount", type = "number"),
            @SearchValueType(name = "userName", type = "String", format = "%%%s%%"),
            @SearchValueType(name = "personName", type = "String", format = "%%%s%%")})
    @ActionRoles("merchandiseExport")
    public String export() {
        Pager pager = new Pager(ServletActionContext.getRequest(), 9999999);
        List<TbCzMerchantListVO> list = null;
        try {
            pager = this.merchantService.listPersonByOrg(this.orgId, pager, getSearchValue());
            list = (List<TbCzMerchantListVO>) pager.getPageData();

        } catch (BaseException e) {
            logger.error("根据机构id获取用户列表异常", e);
        } catch (Exception e) {
            logger.error("根据机构id获取用户列表异常", e);
        } finally {
        }

        if (!AssertUtil.isEmpty(list)) {

            // 调用导出方法，获取导出的文件
            String[] head = {"代理商账号", "代理商名称", "手机号码", "qq号码", "折扣", "代理商余额", "状态", "注册时间", "更新时间", "操作人"};
            File excelFile = ExcelUtil.exportForExcel(head, list, TbCzMerchantListVO.class);
            // 以流的形式输出导出的文件
            try {
                if (excelFile.exists()) {
                    String fileName = "代理商信息" + DateUtil.formartCurrentDate() + ".xls";
                    InputStream is = new FileInputStream(excelFile);
                    HttpServletResponse response = ServletActionContext.getResponse();
                    OutputStream os = response.getOutputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    BufferedOutputStream bos = new BufferedOutputStream(os);

                    fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
                    fileName = new String(fileName.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
                    response.reset();
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("application/ vnd.ms-excel");// 不同类型的文件对应不同的MIME类型

                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    int bytesRead = 0;
                    byte[] buffer = new byte[1024];
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
                    }
                    bos.flush();
                    bis.close();
                    bos.close();
                    is.close();
                    os.close();
                }
            } catch (Exception e) {
                logger.error("导入excel出错", e);
            }
        }

        return null;
    }
}
